<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vue-Learning</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.6/dist/vue.js"></script>

</head>

<body>

  <!-- todolist组件拆分 -->
  <div id="root1">
    <input v-model="inputValue">
    <button @click="handleSubmit">提交</button>

    <ul>
      <todo-item v-for="(item,index) in list"></todo-item>
    </ul>
  </div>
  <script>
    // 全局组件
    Vue.component('todo-item', {
      template: '<li>item</li>'
    })

    new Vue({
      el: "#root1",
      data: {
        inputValue: "",
        list: []
      },
      methods: {
        handleSubmit: function() {
          this.list.push(this.inputValue),
          this.inputValue=""
        }
      }
      
    })

  </script>
  <br>

 <!-- 定义局部组件 -->
 <div id="root2">
    <input v-model="inputValue">
    <button @click="handleSubmit">提交</button>
    <ul>
      <To 
        v-for="(item,index) in list"
        :key="index"
        :content="item">
      </To>
    </ul>
  </div>
  <script>
    // 局部组件
    var TodoItem2 = {
      template: '<li>{{content}}</li>',
      props: ['content']
    }

    new Vue({
      el: "#root2",
      // 局部组件必须在实例中声明
      components: {
        "To": TodoItem2
      },
      data: {
        inputValue: "",
        list: []
      },
      methods: {
        handleSubmit: function() {
          this.list.push(this.inputValue),
          this.inputValue=""
        }
      }
      
    })
  </script>
  <br>

  <!-- todolist删除功能,为了实现删除子组件，必须在父组件中删除子组件的值 -->
  <div id="root3">
      <input v-model="inputValue">
      <button @click="handleSubmit">提交</button>
      <ul>
        <To 
          v-for="(item,index) in list"
          :key="index"
          :content="item"
          :index="index"
          @delete="handleDelete">
          <!-- 监听子组件的delete事件，由此触发父组件的handleDelete事件 -->
        </To>
      </ul>
    </div>
    <script>
      // 局部组件
      var TodoItem2 = {
        // 给li绑定handleClick事件
        template: '<li @click="handleClick">{{content}}</li>',
        props: ['content', 'index'],  // 定义可接收的属性
        methods: {
          handleClick: function() {
            // 向外触发一个delete事件
            this.$emit('delete', this.index)
          },
        }
      }
  
      new Vue({
        el: "#root3",
        // 局部组件必须在实例中声明
        components: {
          "To": TodoItem2
        },
        data: {
          inputValue: "",
          list: []
        },
        methods: {
          handleSubmit: function() {
            this.list.push(this.inputValue),
            this.inputValue=""
          },
          handleDelete: function(index) {
            this.list.splice(index, 1)
          }
        }
        
      })
    </script>

</body>

</html>